package com.chen.mysqltopostgres.util;

import com.chen.mysqltopostgres.constant.Constant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author: cgd
 * @description:
 * @date: 2022/8/22 16:08
 * @version: 1.0
 */
public class SaveFileUtils {
    /**
     * 保存SQL到文件中
     */
    public static void saveSql(List<String> sql, String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists() && !file.createNewFile()) {
            throw new RuntimeException("failed to create file");
        }

        //true表示在文件末尾追加
        FileOutputStream fos = new FileOutputStream(file, true);
        for (String s : sql) {
            fos.write(s.getBytes(StandardCharsets.UTF_8));
            fos.write(Constant.SEPARATOR.getBytes(StandardCharsets.UTF_8));
        }
        fos.close();
    }

    /**
     * 清空文件内容
     */
    public static void emptyFile(String filePath) throws IOException, RuntimeException {
        File file = new File(filePath);
        if (file.exists()) {
            // 清空
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write("".getBytes(StandardCharsets.UTF_8));
            fileOutputStream.close();
        } else {
            throw new RuntimeException("file does not exist");
        }
    }
}
